import { useEffect, useState } from "react"
import { Link } from "react-router-dom"
import { useSelector } from "react-redux"
import { Button, Space, Alert, Tag, message } from "antd"
import useCURD from "../../hooks/useCURD"
import {
  queryList as queryProcessDefinitions,
  queryStartForm
} from '../../apis/processDefinition'
import * as apis from "../../apis/processInstances"
import CommonTable, { createColumn } from "../../components/common/CommonTable"
import ProcessPicker from "../../components/ProcessPicker"
import CommonModalForm from "../../components/common/CommonModalForm"
import { formatFormItems } from "../../utils/formItems"
import ProcessPreviewModal from "../../components/ProcessDesigner/preview/ProcessPreviewModal"
import CommonFilterItem from "../../components/common/CommonFilterItem"


const statusOptions = [
  {
    label: '执行中',
    value: 'running'
  },
  {
    label: '已完成',
    value: 'completed'
  },
  {
    label: '所有',
    value: 'all'
  },
]

const WorkflowProcesses = () => {

  const curApp = useSelector(state => state.appDef.curApp)

  const {
    listData,
    loading,
    query,
    changeQueryValues,
    doQueryList,
  } = useCURD({
    apis,
    moduleName: '流程',
    initQuery: false,
    defaultQuery: {
      sort: 'created-desc',
      state: 'running',
      appDefinitionKey: curApp.appDefinitionKey
    }
  })

  useEffect(() => {
    if (curApp.appDefinitionKey) {
      doQueryList()
    }
  }, [query])

  // 当前app发生切换，刷新列表
  useEffect(() => {
    if (curApp.appDefinitionKey) {
      changeQueryValues({
        appDefinitionKey: curApp.appDefinitionKey
      })
    }
  }, [curApp])

  const columns = [
    {
      key: 'processDefinitionName',
      dataIndex: 'processDefinitionName',
      title: '流程定义',
      width: 200,
      render: (text, rowData) => {
        return <Space>
          {text}
          <Tag color="blue">v{rowData.processDefinitionVersion}</Tag>
        </Space>
      }
    },
    {
      key: 'name',
      dataIndex: 'name',
      title: '流程实例名称'
    },
    createColumn.person({
      dataIndex: 'startedBy',
      title: '创建人',
    }),
    createColumn.time({
      dataIndex: 'started',
      title: '创建时间',
      sorter: true,
      sortOrder: {
        'created-asc': 'ascend',
        'created-desc': 'descend'
      }[query.sort],
    }),
    {
      key: 'status',
      title: '状态',
      width: 100,
      align: 'center',
      render: (rowData) => {
        return rowData.ended ? <Tag color="green">已完成</Tag> : <Tag>进行中</Tag>
      }
    },
    {
      key: 'action',
      title: '操作',
      width: 160,
      align: 'center',
      render: (rowData) => {
        return <Space>
          <Link to={`/workflow/processes/detail/${rowData.id}`}>
            <Button size="small" type="primary">查看详情</Button>
          </Link>
          <ProcessPreviewModal
            processDefinitionId={rowData.id}
            isFinish={!!rowData.ended}
          >
            <Button size="small">显示进度</Button>
          </ProcessPreviewModal>
        </Space>
      }
    }
  ]

  const doQueryProcessDefinitions = () => {
    return queryProcessDefinitions({
      latest: true,
      appDefinitionKey: curApp.appDefinitionKey
    })
  }

  const doCreateProcess = async (values) => {
    try {
      let submitVales
      if (formSetting.initValues.formId) {
        const { name } = values
        delete values.name
        submitVales = {
          ...formSetting.initValues,
          name,
          values: values
        }
      } else {
        submitVales = {
          ...formSetting.initValues,
          ...values
        }
      }
      await apis.createOne(submitVales)
      message.success('流程启动成功！')
      setFormSetting({
        visible: false,
        formItems: [],
        initValues: {}
      })
      doQueryList()
    } catch (error) {
      message.error('流程启动失败！')
    }
  }

  const handlePickProcess = async ([processData]) => {
    if (processData.hasStartForm) {
      // 有启动表单的情况
      const startForm = await queryStartForm(processData.id)
      setFormSetting({
        visible: true,
        initValues: {
          formId: startForm.id,
          processDefinitionId: processData.id
        },
        formItems: [
          {
            label: '流程名称',
            name: 'name',
            required: true
          },
          ...formatFormItems(startForm.fields)
        ]
      })
    } else {
      setFormSetting({
        visible: true,
        initValues: {
          processDefinitionId: processData.id
        },
        formItems: [{
          label: '流程名称',
          name: 'name',
          required: true
        }]
      })
    }
  }

  const [formSetting, setFormSetting] = useState({
    visible: false,
    formItems: [],
    initValues: {}
  })

  const handleTableChange = (pagination, filters, sorter) => {
    const obj = {
      'ascend': 'created-asc',
      'descend': 'created-desc'
    }
    changeQueryValues({
      sort: obj[sorter.order]
    })
  }

  return curApp?.appDefinitionKey ? <div className="page-wrap">
    <CommonModalForm
      title="启动流程"
      {...formSetting}
      onCancel={() => {
        setFormSetting({
          visible: false,
          formItems: [],
          initValues: {}
        })
      }}
      onSubmit={doCreateProcess}
    ></CommonModalForm>
    <div className="page-head">
      <Space>
        <ProcessPicker
          btnText="启动流程"
          multiple={false}
          queryListAction={doQueryProcessDefinitions}
          onPick={handlePickProcess}
        ></ProcessPicker>
      </Space>
      <Space>
        <CommonFilterItem.Radio
          label="流程状态"
          field="state"
          queryValues={query}
          onChangeQueryValues={changeQueryValues}
          options={statusOptions}
        ></CommonFilterItem.Radio>
      </Space>
    </div>
    <div className="page-body">
      <CommonTable
        dataSource={listData}
        columns={columns}
        loading={loading}
        onChange={handleTableChange}
      ></CommonTable>
    </div>
  </div> :
    <div style={{ padding: 20 }}>
      <Alert
        message="对不起，您还没有选择应用"
        description="请先选择应用"
        type="warning"
        showIcon
      />
    </div>
}

export default WorkflowProcesses